const puppeteer = require('puppeteer');
const cheerio = require('cheerio');
async function browserify() {
    const browser = await puppeteer.launch({
        // headless: false,
    });
    return browser;
}
async function setPageCookie(page, cookie, domain) {
    // page 设置cookies
    const cookies = cookie.split(';').map(pair => {
        const name = pair.trim().slice(0, pair.trim().indexOf('='));
        const value = pair.trim().slice(pair.trim().indexOf('=') + 1);
        return { name, value, domain: domain };
    });
    await page.setCookie(...cookies);
    return page;
}
async function launch(urls, cookie='', domain='.douyin.com', functions) {
    let result = [];
    const browser = await browserify();
    let page = await browser.newPage();

    // console.log(cookies);
    for (let i = 0; i < urls.length; i++) {
        let start = Date.now();  // 获取开始时间
        // console.log(puppeteer.executablePath());

        await setPageCookie(page, cookie, domain);
        page.on('response', response => {
            if (response.url().indexOf('aweme/v1/web/aweme/post') > -1) {
                response.json().then(data => {
                    result.push(data['aweme_list']);
                    if (functions.aweme_list && typeof functions.aweme_list === 'function') {
                        functions.aweme_list(data['aweme_list']);
                    }

                });
            }
            if (response.url().indexOf('aweme/v1/web/aweme/detail') > -1) {
                response.json().then(data => {
                    if (functions.aweme_detail && typeof functions.aweme_detail === 'function') {
                        functions.aweme_detail(data['aweme_detail']);
                    }

                });
            }
        });
        await page.goto(urls[i], { waitUntil: 'networkidle2' });
        const title = await page.title();
        console.log(title + '加载中...');

        await page.close();
        page = await browser.newPage();
        let end = Date.now();  // 获取结束时间
        let diff = end - start;  // 计算时间差
        console.log(`Time taken: ${diff / 1000} seconds`);  // 打印时间差（秒）
    }

    await browser.close();
    return result;
}
async function get_user_details(url, cookie, domain, options) {
    let result = {};
    const browser = await browserify();
    let page = await browser.newPage();
    await setPageCookie(page, cookie, domain);
    await page.goto(url, { waitUntil: 'networkidle2' });
    const html = await page.content();
    const $ = cheerio.load(html);
    var renderData = $('#RENDER_DATA').text();
    if (renderData) {
        const jsonData = decodeURIComponent(renderData);
        const json = JSON.parse(jsonData);
        var keys = Object.keys(json);
        for (var i = 0; i < keys.length; i++) {
            var key = keys[i];
            var item = json[key];
            if (item.hasOwnProperty('user')) {
                const uItem = item['user'];
                if (uItem.hasOwnProperty('user')) {
                    const user = uItem['user'];
                    result.uid = user['uid'];
                    result.secUid = user['secUid'];
                    result.nickname = user['nickname'];
                    result.desc = user['desc'];
                    result.roomId = user['roomId'];
                    result.roomData = user['roomData'];
                    // result.liveWebId = user['roomData']['owner']['web_rid'];
                    result.awemeCount = user['awemeCount'];
                    result.followingCount = user['followingCount'];
                    result.followerCount = user['followerCount'];
                    result.totalFavorited = user['totalFavorited'];
                    result.age = user['age'];
                    result.avatarUrl = user['avatarUrl'];
                    result.avatar300Url = user['avatar300Url'];
                    result.gender = user['gender'];
                    result.mplatformFollowersCount = user['mplatformFollowersCount'];
                    result.uniqueId = user['uniqueId'];


                    // console.log(result.roomData)
                    // if(result.roomData.hasOwnProperty('stream_url')){
                    //     const flv_pull_url = result.roomData['stream_url']['flv_pull_url'];
                    //     for(flv in flv_pull_url){
                    //         console.log('xxx')
                    //         console.log(flv + '  '+ flv_pull_url[flv])
                    //     }
                    // }
                }
            }
        }

    }
    return result;
}
module.exports = { launch, get_user_details };